package com.houor.device.controller.handler;

import org.houor.utility.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.houor.device.DeviceConstants;
import com.houor.device.controller.ControllerDataContainer;
import com.houor.device.controller.data.ControllerFrame;
import com.houor.device.controller.data.SensorReportData;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 帧处理器
 * 
 * @author Houor
 *
 * @createTime 2017-04-20 22:58
 */
public class ControllerFrameHandler extends SimpleChannelInboundHandler<ControllerFrame> {
	private static Logger logger = LoggerFactory.getLogger(ControllerFrameHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		logger.debug("There is some exception : {}", cause.getMessage());
		logger.debug("then, close context : {}", ctx);
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ControllerFrame msg) throws Exception {
		logger.info("Object: {}", msg.toString());

		if (ChannelHandlerContextMap.get(msg.getDeviceID()) == null) {
			ChannelHandlerContextMap.put(msg.getDeviceID(), ctx);
		}
		
		SensorReportData srd = new SensorReportData();
		srd.setDeviceId(msg.getDeviceID());
		srd.init(msg.getContent());
		ControllerDataContainer.reportDataQueur.offer(srd);
		logger.debug("Recive Sensor Report: {}", StringUtility.byteArrayToHexString(srd.getBytes()));
		logger.debug("Sensor Report Container Size: {}", ControllerDataContainer.reportDataQueur.size());

		switch (msg.getCommand()) {
		// report data: write data to database
		case DeviceConstants.CONTROLLER_COMMAND_REPORT_SENSOR: {
			
			break;
		}

		// set response data: send to specific context container

		// query response data: send to specific object

		// server command: generate device command and send to controller

		// ctx.channel().writeAndFlush(msg);
		}
		ctx.writeAndFlush(msg);

	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("ChannelHandlerContext {} is active.", ctx);
		// logger.debug("Channel {} is active.", ctx.channel());
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("ChannelHandlerContext {} is Inactive.", ctx);
		// logger.debug("Channel {} is Inactive.", ctx.channel());
		ChannelHandlerContextMap.remove(ctx);
		super.channelInactive(ctx);
	}

}
